import router from '@/router'
import $modal from '@/plugins/modal'
import $store from '@/plugins/store'
const modules = import.meta.glob('../views/**/*.vue')
const hasRoutes = $store.menu.hasRoutes
const menuList = $store.menu.getMenuList()
if (!hasRoutes && menuList != null) {
  // 如果路由没有加载，先加载路由
  bindRoute(menuList)
  $store.menu.setRoutesState(true)
}

// 动态绑定路由
function bindRoute(menuList: Menu[]) {
  const newRoutes = router.options.routes
  menuList.forEach((menu) => {
    if (menu.children) {
      menu.children.forEach((m) => {
        const route = menuToRoute(m, menu.label)
        if (route) {
          newRoutes[0].children.push(route)
        }
      })
    }
  })
  // 重新添加到路由
  newRoutes.forEach((route) => {
    router.addRoute(route)
  })
}
// 菜单对象转成路由对象
function menuToRoute(menu: Menu, parentLabel: string) {
  if (menu.component) {
    const route = {
      name: menu.name,
      path: menu.path,
      // 这里动态路由需要写 ../ 不能@/ ,环境原因
      component: modules[`../views/${menu.component}/index.vue`], // () => import('../views/' + menu.component + '/index.vue'),
      meta: {
        label: menu.label,
        parentLabel: parentLabel
      }
    }
    return route
  }
  return null
}

// 路由前置守卫
router.beforeEach((to, from, next) => {
  const whiteList = ['/login'] // 白名单
  // 加载动态路由
  const token = $store.user.getToken()
  if (token || whiteList.includes(to.path)) {
    next()
  } else {
    $modal.msgError('登录信息已过期！')
    next('/login')
  }
})
